CURRENT_DIR=$(shell pwd)

SRC_DIR=${CURRENT_DIR}/srcdir_t
OBJC_DIR=${CURRENT_DIR}/objcdir_t
OBJS_DIR=${CURRENT_DIR}/objsdir_t
ISO_DIR=${CURRENT_DIR}/isodir_t

GRUB_TEMPLATE=grub.cfg

OS_NAME=Exq-OS
INCLUDE_DIR=${CURRENT_DIR}/includes

LINKER_SCRIPT=${CURRENT_DIR}/linker.ld

QEMU_DEBUG_SYSTEM=qemu-system-i386

CC=i686-elf-gcc

GRUB_CONFIG=${CURRENT_DIR}/${GRUB_TEMPLATE}

C=$(shell find ${CURRENT_DIR} -name "*.c")
S=$(shell find ${CURRENT_DIR} -name "*.S")
H=$(shell find ${CURRENT_DIR} -name "*.h")

# find source file
fsrc:
	@echo ${C}
	@echo ${S}
	@echo ${H}

# make temp dirs
mtdirs:
	@mkdir -p ${SRC_DIR}
	@mkdir -p ${OBJC_DIR}
	@mkdir -p ${OBJS_DIR}

# move source file to ${SRC_DIR}
msrc: fsrc mtdirs
	@cp -f ${C} ${S} ${H} ${SRC_DIR}
	@echo ${shell ls}

clean:
	@rm -rf ${SRC_DIR} ${OBJC_DIR} ${OBJS_DIR} ${ISO_DIR} *.iso grub.cfg

# compile: *.S | *.c -> *.o
compile: mtdirs
	@echo "Entering ${SRC_DIR}"
	cd ${SRC_DIR}
	$(foreach cs, ${C}, ${CC} -c -I ${INCLUDE_DIR} ${cs} -o ${OBJC_DIR}/$(shell basename ${cs} .c).o -std=gnu99 -ffreestanding -O2 -Wall -Wextra;)
	$(foreach ss, ${S}, ${CC} -c -I ${INCLUDE_DIR} ${ss} -o ${OBJS_DIR}/$(shell basename ${ss} .S).o -std=gnu99 -ffreestanding -O2 -Wall -Wextra ;)
	cd ..
	@echo "Leaving ${SRC_DIR}"

# link: *.o -linker.ld-> *.bin
link: compile
	@${CC} -T ${LINKER_SCRIPT} -o ${OS_NAME}.bin -ffreestanding -O2 -nostdlib ${OBJC_DIR}/*.o ${OBJS_DIR}/*.o -lgcc

write_grub_conf:
	@touch grub.cfg
	@echo "menuentry \"${OS_NAME}\" {\n\tmultiboot /boot/${OS_NAME}.bin\n}"  > ${GRUB_CONFIG}

# mkiso: *.bin -> *.iso
mkiso: clean link write_grub_conf
	@mkdir -p ${ISO_DIR}/boot/grub
	@mv ${OS_NAME}.bin ${ISO_DIR}/boot/${OS_NAME}.bin
	@cp ${GRUB_CONFIG} ${ISO_DIR}/boot/grub/$(shell basename ${GRUB_CONFIG})
	@grub-mkrescue -o ${OS_NAME}.iso ${ISO_DIR}

# test with qemu (i386)
qemu-test: mkiso
	@${QEMU_DEBUG_SYSTEM} -cdrom ${OS_NAME}.iso

# test with bochs
bochs-test: mkiso
	@bochs -q -f bochs.cfg